package com.mapper;

import com.pojo.Media;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface MediaMapper {

    // 获取指定笔记的最大排序索引
    @Select("SELECT COALESCE(MAX(order_index), 0) FROM media WHERE note_id = #{noteId}")
    Integer selectMaxOrderIndexByNoteId(Integer noteId);

    @Insert("INSERT INTO media(note_id, media_url, media_type, order_index, created_at) " +
            "VALUES(#{noteId}, #{mediaUrl}, #{mediaType}, #{orderIndex}, #{createdAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Media media);

    @Update("UPDATE media SET " +
            "note_id = #{noteId}, " +
            "media_url = #{mediaUrl}, " +
            "media_type = #{mediaType}, " +
            "order_index = #{orderIndex} " +
            "WHERE id = #{id}")
    int update(Media media);

    @Delete("DELETE FROM media WHERE id = #{id}")
    int delete(Integer id);

    @Delete("DELETE FROM media WHERE note_id = #{noteId}")
    int deleteByNoteId(Integer noteId);

    @Select("SELECT * FROM media WHERE id = #{id}")
    Media selectById(Integer id);

    @Select("SELECT * FROM media WHERE note_id = #{noteId} ORDER BY order_index ASC")
    List<Media> selectByNoteId(Integer noteId);

    @Select("SELECT * FROM media WHERE media_type = #{mediaType}")
    List<Media> selectByMediaType(String mediaType);

    @Update("UPDATE media SET order_index = #{orderIndex} WHERE id = #{id}")
    int updateOrderIndex(@Param("id") Integer id, @Param("orderIndex") Integer orderIndex);

    // 批量插入方法
    @Insert("<script>" +
            "INSERT INTO media(note_id, media_url, media_type, order_index, created_at) VALUES " +
            "<foreach collection='mediaList' item='media' separator=','>" +
            "   (#{media.noteId}, #{media.mediaUrl}, #{media.mediaType}, #{media.orderIndex}, NOW())" +
            "</foreach>" +
            "</script>")
    int batchInsert(@Param("mediaList") List<Media> mediaList);
}